extends Area2D
class_name Bullet

# 导入伤害文本类
const DamageTextClass = preload("res://scripts/ui/damage_text.gd")

## 子弹属性
@export var bullet_count: int = 1  # 子弹数量
@export var damage: int = 4  # 伤害数值
@export var crit_rate: float = 0.5  # 暴击率 (50%)
@export var crit_damage_multiplier: float = 1.5  # 暴击效果 (50%额外伤害)
@export var speed: float = 300.0  # 子弹速度
@export var lifetime: float = 2.0  # 存在时间 (2秒)
@export var pierce_count: int = 0  # 穿透数量
@export var damage_type: String = "无"  # 伤害类型
@export var spread_angle: float = 8.0  # 散射角度 (8度)
@export var hitbox_radius: float = 6.0  # 碰撞半径（与 bullet.tscn 默认 CircleShape2D 匹配）
@export var energy_cost: int = 2  # 能量需求

## 私有变量
var direction: Vector2 = Vector2.RIGHT
var pierced_enemies: Array = []
var lifetime_timer: float = 0.0
var is_destroyed: bool = false  # 防止重复处理

## 组件引用
@onready var sprite: Sprite2D = $Sprite2D
@onready var collision_shape: CollisionShape2D = $CollisionShape2D

func _ready():
	# 连接信号
	body_entered.connect(_on_body_entered)
	
	# 设置生命周期
	lifetime_timer = lifetime

	# 同步碰撞半径到场景形状
	if collision_shape and collision_shape.shape is CircleShape2D:
		var circle: CircleShape2D = collision_shape.shape as CircleShape2D
		circle.radius = hitbox_radius
	
	# 创建子弹外观
	create_bullet_sprite()

func _physics_process(delta):
	# 移动子弹
	# 速度下限为 0（防止负速度导致反向或异常）
	speed = max(0.0, speed)
	global_position += direction * speed * delta
	
	# 更新生命周期
	lifetime_timer -= delta
	if lifetime_timer <= 0:
		destroy_bullet()

func create_bullet_sprite():
	# 创建圆形子弹外观
	var texture := ImageTexture.new()
	var image := Image.create(12, 12, false, Image.FORMAT_RGBA8)
	
	# 绘制圆形
	draw_circle_on_image(image, Color.WHITE)
	
	texture.set_image(image)
	if sprite:
		sprite.texture = texture
		sprite.scale = Vector2(0.7, 0.7)

func set_direction(new_direction: Vector2):
	direction = new_direction.normalized()
	
	# 旋转子弹朝向
	if sprite:
		sprite.rotation = direction.angle()

func _on_body_entered(body):
	# 如果子弹已经被销毁，直接返回
	if is_destroyed:
		return
		
	# 排除玩家和已经穿透的敌人
	if body.is_in_group("player") or body in pierced_enemies:
		return
	
	# 如果是敌人，造成伤害
	if body.has_method("take_damage"):
		# 先判断是否暴击，然后计算伤害
		var is_critical := is_crit_hit()
		var final_damage := calculate_damage(is_critical)
		
		# 显示伤害数值
		show_damage_text(final_damage, body.global_position, is_critical)
		
		body.take_damage(final_damage)
		
		# 添加到已穿透列表
		pierced_enemies.append(body)
		
		# 检查是否还能穿透（穿透数量0意味着只能命中1个敌人）
		if pierced_enemies.size() > pierce_count:
			destroy_bullet()

func calculate_damage(is_critical: bool) -> int:
	var final_damage := damage
	if is_critical:
		final_damage = int(damage * crit_damage_multiplier)
	return final_damage

func is_crit_hit() -> bool:
	return randf() < crit_rate

func show_damage_text(damage_amount: int, pos: Vector2, is_critical: bool):
	# 创建伤害文本
	var damage_text = DamageTextClass.create_damage_text(damage_amount, pos, is_critical)
	# 添加到场景中
	get_tree().current_scene.add_child(damage_text)

func destroy_bullet():
	if not is_destroyed:
		is_destroyed = true
		queue_free()

## 在图像上绘制圆形
func draw_circle_on_image(image: Image, color: Color):
	var w := image.get_width()
	var h := image.get_height()
	var center := Vector2(w / 2.0, h / 2.0)
	var radius: float = float(min(w, h)) * 0.5
	for y in range(h):
		for x in range(w):
			var p := Vector2(x + 0.5, y + 0.5)
			if p.distance_to(center) <= radius:
				image.set_pixel(x, y, color)
			else:
				image.set_pixel(x, y, Color(0, 0, 0, 0))
